<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/19
 * Time: 9:38
 */

namespace app\api\service;


use app\lib\exception\ParameterException;
use Driver\Cache\Redis;

class TongdunService
{
    private $data;
    private $tongdun;
    private $hit_rule = array();
    private $all_type = array();
    private $personal;
    public function __construct($post)#post
    {
        # 实例化同盾接口
        $this->tongdun = new \Tongdun\TongDunApi();
        # 根据 三要素（姓名，手机，身份证）初步查询数据
        $this->data = $this->serviceApi($post);
    }

    /**
     * 初始化自动调用该方法
     * @param $post 客户端传过来的数据
     * @return mixed
     * @throws ParameterException
     */
    private function serviceApi($post)
    {
        # 调用供风险决策接口
        $json_result = $this->tongdun->serviceApi($post);
        # 得到json数据转化成php数组
        $date = json_decode($json_result,true);
        # 如果 success == false 不存在则抛出异常
        if(!$date['success']){
            throw new ParameterException([
                'msg' => $date,
            ]);
        }
        # 获取个人详情资料以及 sequence_id
        $this->personal = $this->getPersonal($post, $date);
        return $date;
    }

    /**
     * 个人详情资料
     * @param $post
     * @param $date
     * @return array
     */
    private function getPersonal($post,$date)
    {
        $personal = array();
        $personal['name'] = $post['name'];
        $personal['id_number'] = $post['id_number'];
        $personal['mobile'] = $post['mobile'];
        $birth_year = substr($post['id_number'],6, 4);
        $age= date('Y') - $birth_year;
        $personal['age'] = $age;
        if(substr($post['id_number'],16, 1) % 2 == 0){
            $personal['sex'] = "女";
        }else{
            $personal['sex'] = "男";
        }
        $personal['sequence_id'] = $date['seq_id'];
        $grade = $date['final_decision'];
        if($grade == 'Accept'){
            $date['final_decision'] = '无风险';
        }elseif ($grade == 'Review'){
            $date['final_decision'] = '低风险';
        }elseif ($grade == 'Reject'){
            $date['final_decision'] = '高风险';
        }
        $personal['decision'] = $date['final_decision'];
        $personal['address'] = implode('',$date['attribution']);
        $score = round($date['final_score']*0.8);
        if($score > 100) {
            $personal['score'] = 100;
            $personal['credit_card'] = 0.1;
            $personal['net_loan'] = 0.1;
        }else{
            $personal['score'] = $score;
            $personal['credit_card'] = 100 - $personal['score'];
            $net_loan = (100 - $personal['score'])*1.5;
            if($net_loan >= 100){
                $net_loan = 99;
            }
            $personal['net_loan'] = $net_loan;
        }
        $personal['grade'] = $this->score($personal['score']);
        $personal['create_time'] = now_time();
        return $personal;
    }

    public function tongdun()
    {
        # 根据 sequence_id 查询出更加详情的命中规则数据
        $sequence_id = $this->tongdun->ruleApi([
            'sequence_id'=>$this->data['seq_id']
        ]);
        # 获取所有type的命中规则（数据没有处理）
        $result = $this->returnTongdun($sequence_id);

        # 对上一步获取的数据进行下一步处理
        $conditions = new ConditionFun();
        $date_rules = $conditions->getConditionsData($result);
        $date_service = $conditions->getService($this->data);
        $result =  array(
            'personal' => $this->personal,
            'hit_rule' => $this->hit_rule,
            'grey_list' => $date_rules['grey_list'],
            'black_list' => $date_rules['black_list'],
            'discredit_count' => $date_rules['discredit_count'],
            'cross_partner' => $date_rules['cross_partner'],
            'execute_court' => $date_rules['execute_court'],
            'frequency_distinct' => $date_rules['frequency_distinct'],
            'frequency_one_dim' => $date_rules['frequency_one_dim'],
            'risk' => $date_service['hit_rules'],
        );
        $tongdunServiceArr = new tongdunServiceArr($result);
        $result = $tongdunServiceArr->ConditionFun();
        return $result;
    }
    # 对命中规则rule进行提取
    private function returnTongdun($rule_data)
    {
        $ruleApi = json_decode($rule_data,true);
        if(!$ruleApi['success']){
            throw new ParameterException($ruleApi);
        }
        $rules = $ruleApi['rules'];
        # 使用递归的方式进行遍历多维数组
        $arr = $this->MulitarraytoSingle($rules);
        return $arr;
    }

    /**
     * 核心方法，使用递归获取多维数组
     * @param $array
     * @return array
     */
    private function MulitarraytoSingle($array)
    {
        $data = array();
        if(is_array($array)){
            foreach ($array as $key => $value )
            {
                if(is_array($value)){
                    if(array_key_exists('conditions',$value)){
                        $conditionsArr = $this->conditionsArr($value['conditions']);
                        if($conditionsArr !== null){
                            if(in_array($conditionsArr,$data) == false){
                                $conditionsArr['score'] = $value['score'];
                                array_push($data,$conditionsArr);
                            }
                        }
                    }
                    $this->MulitarraytoSingle($value);
                }
            }
        }
        return $data;
    }

    /**
     * 通过循环判断type的值
     * @param $conditions
     * @return null
     */
    private function conditionsArr($conditions)
    {
        $conditionsArr = null;
        # conditions数组
        foreach ($conditions as $key => $condition) {
            $type = $condition['type'];
            array_push($this->all_type, $type);
            if ($type == 'cross_partner') {
                # 命中了多平台借贷统计
                unset($condition['hits_for_dim']);
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了多平台借贷统计');
            }
            if ($type == 'grey_list') {
                # 命中了关注名单规则
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了关注名单规则');
            }
            if ($type == 'frequency_distinct') {
                # 命中了频度关联个数统计
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了频度关联个数统计');
            }
            if ($type == 'discredit_count') {
                # 命中了信贷逾期统计规则
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了信贷逾期统计规则');
            }
            if ($type == 'suspected_team') {
                # 命中了风险群体规则
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了风险群体规则');
            }
            if ($type == 'black_list') {
                # 命中了风险名单规则
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了风险名单规则');
            }
            if ($type == 'match_address') {
                # 命中了地址位置匹配规则
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了地址位置匹配规则');
            }
            if ($type == 'keyword') {
                # 命中了信贷名单库
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了信贷名单库');
            }
            if ($type == 'creditList_index_detail') {
                # 命中了关键词表
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了关键词表');
            }
            if ($type == 'frequency_one_dim') {
                # 命中了频度出现次数统计
                $conditionsArr = $condition;
                $this->hit_rule($type, '命中了频度出现次数统计');
            }

        }
        return $conditionsArr;
    }

    /**
     * @param $type 命中规则类型（key）
     * @param $value 命中规则类型（value）
     */
    private function hit_rule($type, $value)
    {
        if(array_key_exists($type,$this->hit_rule) == false){
            $this->hit_rule[$type] = $value;
        }else{
            return ;
        }
    }

    private function score($score)
    {
        switch ($score)
        {
            case $score >= 90 && $score <= 100:
                return "您的风险指数过高/资质极差，急需提升/网贷重患，闻风丧胆";
            case $score < 90 && $score >= 80:
                return "您的风险指数偏高/资质偏差，有待提升/网贷偏重";
            case $score < 80 && $score >= 60:
                return "您的风险指数中等/资质一般，还需提升/日常网贷";
            case $score < 60 && $score >= 40:
                return "您的风险指数较小/资质良好，继续保持/偶尔网贷";
            case $score < 40 && $score >= 20:
                return "您的风险指数偏小/资质较好，继续保持/极少网贷";
            case $score < 20 && $score >= 0:
                return "您的风险指数极小/资质优秀，继续保持/极少网贷";
        }
    }
}